classdef GUICreator < handle
    properties
        figureHandle
        uiHandle
    end
    methods
        function obj = GUICreator(varargin)
            p=inputParser;
            p.addParameter('Width', 0.8, @(x) isnumeric(x) && x > 0);
            p.addParameter('Height', 0.8,  @(x) isnumeric(x) && x > 0);
            p.addParameter('Name', 'No Name', @ischar);
            p.addParameter('Unit', 'Relative', @(x) ismember(x, {'Relative', 'Absolute'}));
            p.addParameter('isShow', false, @islogical);
            p.parse(varargin{:});
            
            obj.make_figure(p.Results.Width, p.Results.Height, p.Results.Name, p.Results.isShow,  p.Results.Unit);
        end
        function delete(obj)
            L = log4m.getLogger;
            if isvalid(obj.figureHandle)
                delete(obj.figureHandle);
                L.info('GUICreator::delete', 'UIFigure deleted.');
            end
        end
        
        function show(obj)
            obj.figureHandle.Visible = true;
        end
        
        function hide(obj)
            obj.figureHandle.Visible = false;
        end
        
        function tf = isShown(obj)
            tf = strcmp(obj.figureHandle.Visible, 'on');
        end
        
        function make_figure(obj, width, height, title, isShow, unit)
            mp = get(0, 'MonitorPositions'); winWidth = mp(1, 3); winHeight = mp(1, 4);
            switch unit
                case 'Relative'
                    pos = [0.5*(1-width)*winWidth, 0.5*(1-height)*winHeight, width*winWidth, height*winHeight];
                case 'Absolute'
                    pos = [0.5*(winWidth-width), 0.5*(winHeight-height), width, height];
                otherwise
                    error('Unknown Unit option');
            end
            obj.figureHandle = uifigure('Visible', 'off', 'Position', pos, 'Name', title, 'CloseRequestFcn',@(f, event) obj.closeReq());
            obj.figureHandle.Visible = isShow;
        end
        
        function grid = make_grid(obj, parent, sz, varargin)
            p=inputParser;
            p.addRequired('parent', @(x) isempty(x) || isa(x,  'matlab.ui.container.Panel') || isa(x, 'matlab.ui.Figure'));
            p.addRequired('sz', @(x) isnumeric(x) && length(x) == 2 && all(x>0));
            p.addParameter('RowHeight', {'1x', '1x'}, @iscell);
            p.addParameter('ColumnWidth', {'1x', '1x'}, @iscell);
            p.addParameter('Padding', [0 0 0 0], @(x) isnumeric(x) && length(x) == 4);
            p.parse(parent, sz, varargin{:});
            
            if isempty(parent)
                parent = obj.figureHandle;
            end
            grid = Miscellaneous.GUICreator.GridLayoutEx(parent, sz, varargin{:});
        end
        
        function closeReq(obj)
            obj.hide();
        end
    end
end

